package my.model;

import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import chen.util.DbUtil;

public class MenuModel{
	
	public int add(Map<String,Object> args) {
		try {
			return DbUtil.dao.save(this, args);
		}catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	public int edit(Map<String,Object> args) {
		try {
			return DbUtil.dao.update(this, args, "id=#id#");
		}catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}
	public int delete(Map<String,Object> args) {
		try {
			return DbUtil.dao.delete(this, args, "id=#id#");
		}catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	public String loadAllMenu(Map<String,Object> args) {
		return this.loadMenu(selectAllMenu,null);
	}
	
	public String loadMenuById(Map<String,Object> args) {
		if(args.get("id") == null){
			args.put("id","0");
		}
		return this.loadMenu(selectMenuById,args);
	}
	
	public String loadMenu(String sql,Map<String,Object> args) {
		try {
			List<Map<String, Object>> menus = null;
			if(args == null){
				menus = DbUtil.dao.query(sql);
			}else{
				menus = DbUtil.dao.query(sql,args);
			}
			return JSONArray.fromObject(menus).toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	private String selectAllMenu = "select id,pid,name,url,leaf,icon,'modal' mode from menu order by ord asc";
	private String selectMenuById = "select id,pid,name,url,leaf,icon,'modal' mode,decode(leaf,'1','','closed') state from menu where pid=#id# order by ord asc";
}